package org.edu.modules.oa.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.RedisUtil;
import org.edu.modules.oa.entity.VeFileFilesEntity;
import org.edu.modules.oa.entity.VeOaMobileMsgEntity;
import org.edu.modules.oa.entity.VeOaNoticeEntity;
import org.edu.modules.oa.entity.VeOaTongxunluEntity;
import org.edu.modules.oa.mapper.IVeOaMobileMessageMapper;
import org.edu.modules.oa.mapper.IVeOaNoticeMapper;
import org.edu.modules.oa.mapper.IVeOaNoticeUserMapper;
import org.edu.modules.oa.mapper.IVeOaTongxunluMapper;
import org.edu.modules.oa.service.IVeOaMobileMsgService;
import org.edu.modules.oa.service.IVeOaNoticeService;
import org.edu.modules.oa.util.OssDownloadUtil;
import org.edu.modules.oa.vo.VeOaMobileMsgExportVo;
import org.edu.modules.oa.vo.VeOaNoticeExportVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;

@Api(tags="手机短信")
@RestController
@RequestMapping("oa/veOaMobileMsg")
@Slf4j
@ApiSort(value = 100)
public class VeOaMobileMessageController {
    @Resource
    private IVeOaMobileMessageMapper iVeOaMobileMessageMapper;
    @Resource
    private IVeOaMobileMsgService iVeOaMobileMsgService;
    @Resource
    private IVeOaTongxunluMapper iVeOaTongxunluMapper;




    //获取通讯录用户
    @AutoLog(value = "手机短信-获取通讯录用户")
    @ApiOperation(value="获取通讯录用户", notes="手机短信-获取通讯录用户")
    @PostMapping(value = "/getTxl")
    public  Result getTxl(String ids){
        String[]  idArr= ids.split(",");
        String readers="";
        ArrayList<VeOaTongxunluEntity> arr = (ArrayList<VeOaTongxunluEntity>) iVeOaTongxunluMapper.selectByMap(null);
        for (VeOaTongxunluEntity o : arr) {
            for (String s : idArr) {
                if(Integer.parseInt(s)==o.getId()){
                    readers=o.getUserName()+","+readers;
                }
            }
        }

        return Result.OK(readers);
    }
    // 增加手机短信
    @AutoLog(value = "手机短信-增加短信")
    @ApiOperation(value="增加短信", notes="手机短信-增加短信")
    @PostMapping(value = "/addMsg")
    public Result addMsg(VeOaMobileMsgEntity veOaMobileMsgEntity) throws ParseException {

        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        veOaMobileMsgEntity.setCreateBy(user.getRealname());
        veOaMobileMsgEntity.setIsDeleted(0);
        veOaMobileMsgEntity.setTerminalId(0);
        veOaMobileMsgEntity.setCreateUserid(user.getId());

        int result= iVeOaMobileMessageMapper.insert(veOaMobileMsgEntity);

        return Result.OK(result);
    }
    // 修改公告信息
    @AutoLog(value = "手机短信-修改公告")
    @ApiOperation(value="修改公告", notes="手机短信-修改公告")
    @PostMapping(value = "/amendMobileMsg")
    public Result amendNotice(MultipartFile file,VeOaMobileMsgEntity veOaMobileMsgEntity) throws ParseException {

       veOaMobileMsgEntity.setContent(delHtmlTag(veOaMobileMsgEntity.getContent().replaceAll("\\<.*?>","")));

       int result=0;
            try {
         result= iVeOaMobileMessageMapper.updateById(veOaMobileMsgEntity);
    } catch (Exception e) {
        return Result.error(500,"表格数据有问题不能上传");
    }
        return Result.OK(result);
    }
    public static String delHtmlTag(String str){

        String newstr = "";

        newstr = str.replaceAll("<[.[^>]]*>","");

        newstr = newstr.replaceAll(" ", "");

        return newstr;

    }
    @AutoLog(value = "手机短信-显示表格")
    @ApiOperation(value="显示表格", notes="手机短信-显示表格")
    @PostMapping(value = "/showTable")
    public Result<?> showTable( Integer startPage, Integer pageSize,VeOaMobileMsgEntity veOaMobileMsgEntity) {

        HashMap<String, Object> map=iVeOaMobileMsgService.showTable(startPage,pageSize,veOaMobileMsgEntity);
        // 获取redis存的用户值

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        map.put("userName",user.getRealname());
        return Result.OK(map);
    }
    @AutoLog(value ="手机短信-单个删除")
    @ApiOperation(value="单个删除", notes="手机短信-单个删除")
    @PostMapping(value = "/oneDelete")
    public Result<?> oneDelete(Integer id) {
        Integer result=iVeOaMobileMsgService.deleteRecord((long)id);
        return Result.OK();
    }
    @AutoLog(value = "手机短信-批量删除")
    @ApiOperation(value="批量删除", notes="手机短信-批量删除")
    @PostMapping(value = "/allDelete")
    public Result<?> allDelete(String idStr) {

        Integer result=0;
        String data[] = idStr.split(",");

        for (int i=1;i<data.length;i++){

            result+=iVeOaMobileMsgService.deleteRecord(Long.parseLong(data[i]));

        }
        return Result.OK();
    }

    //导出
    @AutoLog(value = "手机短信-导出excel表格")
    @ApiOperation(value = "导出excel表格", notes = "手机短信—导出excel表格")
    @GetMapping(value = "/exportTable")
    // ModelAndView 导出表格流
    public ModelAndView exportTable() {
        // 创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 查数据获得的集合
        List<VeOaMobileMsgExportVo> list = iVeOaMobileMsgService.xporte();
        // 文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME, "手机短信");
        // 数据的类型
        mv.addObject(NormalExcelConstants.CLASS, VeOaMobileMsgExportVo.class);
        // 获取redis存的用户值

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("手机短信", "导出人:" + user.getRealname(), "导出手机短信");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }
    //导入
    @AutoLog(value = "手机短信-导入")
    @ApiOperation(value = "导入", notes = "手机短信-导入")
    @PostMapping(value = "/importExcel")
    public Result<?>importExcel(HttpServletRequest req, HttpServletResponse resp){
        //先把需要导入的文件上传
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        //获取上传的文件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        //取出来
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                //上传的数据的集合(list就是文件里所有内容)
                List<VeOaMobileMsgExportVo> list = ExcelImportUtil.importExcel(file.getInputStream(), VeOaMobileMsgExportVo.class, params);
                System.out.println("================"+list.size()+"================");
                // 获取redis存的用户值
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                //加入数据库使用的集合
                List<VeOaMobileMsgEntity> entityList =new ArrayList<>();
                //循环遍历把需要的字段拷贝到数据库插入的集合中
                for(VeOaMobileMsgExportVo v : list){
                    System.out.println("=============================");
                    System.out.println(v);
                    System.out.println("=============================");
                    VeOaMobileMsgEntity veOaMobileMsgEntity = new VeOaMobileMsgEntity();

                    veOaMobileMsgEntity.setIsDeleted(0);
                    veOaMobileMsgEntity.setContent(v.getContent());
                    veOaMobileMsgEntity.setCreateBy(v.getCreateBy());
                    veOaMobileMsgEntity.setMsgType(v.getMsgType());
                    veOaMobileMsgEntity.setReaders(v.getReaders());

                    veOaMobileMsgEntity.setTerminalId(0);
                    entityList.add(veOaMobileMsgEntity);
                }
                iVeOaMobileMsgService.saveBatch(entityList);
                return Result.ok("文件导入成功！数据行数：" + entityList.size());
            } catch (Exception e) {
                return Result.error("文件导入格式须为电子表格");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //导出excel模板
    @AutoLog(value = "手机短信-导出excel模板")
    @ApiOperation(value = "导出excel模板", notes = "手机短信—导出excel模板")
    @GetMapping(value = "exportModel")
    public ModelAndView exportModel() {
        // 创建导出流

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 文件的文件名

        mv.addObject(NormalExcelConstants.FILE_NAME, "手机短信");
        mv.addObject(NormalExcelConstants.CLASS, VeOaMobileMsgExportVo.class);
        // 获取redis存的用户值

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）

        ExportParams exportParams = new ExportParams("手机短信记录", "导出人:" + user.getRealname(), "导出手机短信记录");

        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, new ArrayList<VeOaMobileMsgExportVo>());
        return mv;
    }
    //获取模板下载地址
    @AutoLog(value = "手机短信-模板地址获取")
    @ApiOperation(value = "模板地址", notes = "手机短信-模板地址获取")
    @PostMapping(value = "/getUrl")
    public Result<T> getUrl() throws Exception {
        Result result = new Result();
        String url= OssDownloadUtil.getOssDownloadUtil().downFileFromOSS("手机短信模板.xls");
        result.success(url);
        return result;
    }

}
